package com.caipin.controller;

import com.caipin.domain.table.CourseSubjects;
import com.caipin.domain.table.CourseTable;
import com.caipin.domain.table.CourseTimetable;
import com.caipin.domain.web.PageBean;
import com.caipin.domain.web.ResultJson;
import com.caipin.service.CourseManagementService;
import com.caipin.utils.ImportExcel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-07-30 14:59
 * @Description: TODO
 */
@RestController
@RequestMapping({"/courseManagement"})
public class CourseManagementController {
    @Autowired
    private CourseManagementService courseManagementService;

    @PostMapping({"/timetableImport"})
    public Object timetableImport(@RequestParam("timetable") MultipartFile file, HttpServletRequest request) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<CourseTimetable> timetableList = ImportExcel.importExcel(inputStream, 1, 0, CourseTimetable.class);
        int count = this.courseManagementService.importTimeTableToMysql(timetableList);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @GetMapping({"/timetableList"})
    public Object timetableList() {
        List<CourseTimetable> courseTimetableList = this.courseManagementService.findCourseTimetableList();
        return ResultJson.ok(courseTimetableList);
    }

    @GetMapping({"/getTimetable/{timetableId}"})
    public Object getTimetable(@PathVariable("timetableId") Long id) {
        CourseTimetable courseTimetable = this.courseManagementService.findCourseTimetableById(id);
        return ResultJson.ok(courseTimetable);
    }

    @PostMapping({"/addTimetable"})
    public Object addTimetable(@RequestBody CourseTimetable courseTimetable) {
        this.courseManagementService.addCourseTimetable(courseTimetable);
        return ResultJson.ok();
    }

    @PutMapping({"/modifyTimetable"})
    public Object modifyTimetable(@RequestBody CourseTimetable courseTimetable) {
        this.courseManagementService.updateCourseTimetable(courseTimetable);
        return ResultJson.ok();
    }

    @PostMapping({"/courseSubjectsImport"})
    public Object courseSubjectsImport(@RequestParam("courseSubjects") MultipartFile file, HttpServletRequest request) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<CourseSubjects> courseSubjectsList = ImportExcel.importExcel(inputStream, 1, 0, CourseSubjects.class);
        int count = this.courseManagementService.importCourseSubjectsToMysql(courseSubjectsList);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @GetMapping({"/courseSubjectsList"})
    public Object courseSubjectsList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize, @RequestParam(value = "school_year", required = false) String schoolYear, @RequestParam(value = "semester", required = false) Integer semester, @RequestParam(value = "course_name", required = false) String courseName, @RequestParam(value = "course_type", required = false) String courseType, @RequestParam(value = "grade", required = false) String grade, @RequestParam(value = "classroom", required = false) String classroom) {
        PageBean<CourseSubjects> pageBean = null;
        if (schoolYear == null && semester == null && courseName == null && courseType == null && grade == null && classroom == null) {
            pageBean = this.courseManagementService.findCourseSubjectsList(pageNum, pageSize);
        } else {
            pageBean = this.courseManagementService.findCourseSubjectsList(pageNum, pageSize, schoolYear, semester, courseName, courseType, grade, classroom);
        }
        return ResultJson.ok(pageBean);
    }

    @GetMapping({"/getCourseSubjects/{courseSubjectId}"})
    public Object getCourseSubjects(@PathVariable("courseSubjectId") Long id) {
        CourseSubjects courseSubjects = this.courseManagementService.findCourseSubjectsById(id);
        return ResultJson.ok(courseSubjects);
    }

    @DeleteMapping({"/delCourseSubjects/{courseSubjectId}"})
    public Object delCourseSubjects(@PathVariable("courseSubjectId") Long id) {
        this.courseManagementService.delCourseSubjectsById(id);
        return ResultJson.ok();
    }

    @PostMapping({"/addCourseSubjects"})
    public Object addCourseSubjects(@RequestBody CourseSubjects courseSubjects) {
        this.courseManagementService.addCourseSubjects(courseSubjects);
        return ResultJson.ok();
    }

    @PutMapping({"/modifyCourseSubjects"})
    public Object modifyCourseSubjects(@RequestBody CourseSubjects courseSubjects) {
        this.courseManagementService.updateCourseSubjects(courseSubjects);
        return ResultJson.ok();
    }

    @PostMapping({"/courseTableImport"})
    public Object courseTableImport(@RequestParam("courseTable") MultipartFile file, HttpServletRequest request) throws IOException {
        List<CourseTable> courseTables = new ArrayList<>();
        InputStream inputStream = file.getInputStream();
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        int maxSections = this.courseManagementService.getCourseMaxSections();
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            HSSFSheet sheet = workbook.getSheetAt(i);
            String grade = sheet.getSheetName();
            for (int j = 3; j <= sheet.getLastRowNum(); j++) {
                HSSFCell cell = sheet.getRow(j).getCell(0);
                if (null == cell)
                    break;
                String stringCellValue = cell.getStringCellValue();
                stringCellValue.replaceAll("\r|\n", "");
                String[] strings = stringCellValue.split(" +");
                String clbum = strings[0];
                String[] position = strings[1].split("-");
                String building = position[0];
                String classroom = position[1];
                for (int k = 1; k < sheet.getRow(0).getLastCellNum(); k++) {
                    int week = 0;
                    if (k >= 1 && k <= maxSections) {
                        week = 1;
                    } else if (k >= 1 + maxSections && k <= maxSections * 2) {
                        week = 2;
                    } else if (k >= maxSections * 2 + 1 && k <= maxSections * 3) {
                        week = 3;
                    } else if (k >= maxSections * 3 + 1 && k <= maxSections * 4) {
                        week = 4;
                    } else if (k >= maxSections * 4 + 1 && k <= maxSections * 5) {
                        week = 5;
                    }
                    int sections = 0;
                    if (k >= 1 && k <= maxSections) {
                        sections = k;
                    } else {
                        int value = k % maxSections;
                        if (value == 0) {
                            sections = maxSections;
                        } else {
                            sections = value;
                        }
                    }
                    if (ImportExcel.isMergedRegion((Sheet)sheet, j, k).booleanValue()) {
                        String mergedRegionValue = ImportExcel.getMergedRegionValue((Sheet)sheet, j, k);
                        mergedRegionValue.replaceAll("\r|\n", "");
                        String[] courseList = mergedRegionValue.split(" +");
                        for (String s : courseList) {
                            CourseTable courseTable = (new CourseTable()).setGrade(grade).setClbum(clbum).setWeek(Integer.valueOf(week)).setSections(Integer.valueOf(sections)).setBuilding(building).setClassroom(classroom).setCourseName(s);
                            courseTables.add(courseTable.setCourseName(s));
                        }
                    } else {
                        String course = sheet.getRow(j).getCell(k).getStringCellValue();
                        CourseTable courseTable = (new CourseTable()).setGrade(grade).setClbum(clbum).setWeek(Integer.valueOf(week)).setSections(Integer.valueOf(sections)).setBuilding(building).setClassroom(classroom).setCourseName(course);
                        courseTables.add(courseTable.setCourseName(course));
                    }
                }
            }
        }
        int count = this.courseManagementService.importCourseTableToMysql(courseTables);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @GetMapping({"/courseTableList"})
    public Object courseTableList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize, @RequestParam(value = "grade", required = false) String grade, @RequestParam(value = "clbum", required = false) String clbum, @RequestParam(value = "week", required = false) Integer week, @RequestParam(value = "sections", required = false) Integer sections, @RequestParam(value = "course_name", required = false) String course_name) {
        PageBean<CourseTable> pageBean = null;
        if (grade == null && clbum == null && week == null && sections == null && course_name == null) {
            pageBean = this.courseManagementService.findCourseTableList(pageNum, pageSize);
        } else {
            pageBean = this.courseManagementService.findCourseTableList(pageNum, pageSize, grade, clbum, week, sections, course_name);
        }
        return ResultJson.ok(pageBean);
    }

    @DeleteMapping({"/delCourseTableList"})
    public Object delCourseTableList(@RequestBody List<Integer> ids) {
        int count = this.courseManagementService.delCourseTableList(ids);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @DeleteMapping({"/delCourseTable/{courseTableId}"})
    public Object delCourseTable(@PathVariable("courseTableId") Integer id) {
        this.courseManagementService.delCourseTable(id);
        return ResultJson.ok();
    }

    @GetMapping({"/getCourseTable/{courseTableId}"})
    public Object getCourseTable(@PathVariable("courseTableId") Long id) {
        CourseTable courseTable = this.courseManagementService.findCourseTableById(id);
        return ResultJson.ok(courseTable);
    }

    @PutMapping({"/modifyCourseTable"})
    public Object modifyCourseTable(@RequestBody CourseTable courseTable) {
        this.courseManagementService.updateCourseTable(courseTable);
        return ResultJson.ok();
    }

    @PostMapping({"/addCourseTable"})
    public Object addCourseTable(@RequestBody CourseTable courseTable) {
        this.courseManagementService.addCourseTable(courseTable);
        return ResultJson.ok();
    }
}
